package com.mall.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mall.exception.MyException;
import com.mall.model.User;
import com.mall.service.UserService;
import com.mall.util.MyUtil;

@Controller
@RequestMapping("/user")
public class UserController extends MyUtil {
	@Autowired
	private UserService userService;
	@Autowired
	private MyUtil myUtil;

	/**
	 * 个人中心
	 * 
	 * @throws Exception
	 *
	 * @dagewang 2017年9月19日
	 */
	@RequestMapping("/center")
	public String center(HttpSession session, Model model) throws Exception {
		User user = (User) session.getAttribute("user");
		if (user != null) {
			User user2 = userService.getUser(user.getId());
			user2.setUsername(null);
			user2.setPassword(null);
			model.addAttribute("center", user2);
			return "userCenterSet";
		}
		return "login";
	}

	/**
	 * 修改密码
	 * 
	 * @dagewang 2017年9月20日
	 */
	@RequestMapping("/updatePwd")
	public @ResponseBody Map<String, Object> updatePwd(String pwd1, String pwd2, HttpSession session) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		if (this.isNull(pwd1, pwd2)) {
			map.put("result", 0);
			map.put("error", "修改密码失败,请稍后再试!");
		}
		User user = (User) session.getAttribute("user");
		if (user == null) {
			map.put("result", 3);
		} else {
			User get = userService.getUser(user.getId());
			if (get != null) {
				if (get.getPassword().equals(pwd1)) {
					get.setPassword(pwd2);
					int update = userService.update(get);
					map.put("result", update);
					if (update == 0) {
						map.put("error", "修改密码失败,请稍后再试!");
					}
				}
			}
		}

		return map;
	}

	/**
	 * 更新用户信息
	 * 
	 * @dagewang 2017年9月19日
	 */
	@RequestMapping("/update")
	public @ResponseBody Integer update(User user, HttpSession session, String brithString) throws Exception {
		if (this.isNull(user.getName(), brithString, user.getGender())) {
			return 0;
		}
		if (user.getImg().equals("")) {
			user.setImg(null);
		}

		User get = (User) session.getAttribute("user");
		if (user.getName().equals("管理员") && get.getId() != 3) {
			return 0;
		}
		if (get == null) {
			return 0;
		}
		user.setId(get.getId());
		if (!(this.isNull(brithString))) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date date = sdf.parse(brithString);
			user.setBirthday(date);
		}
		int result = userService.update(user);
		return result;
	}

	/**
	 * 上传头像
	 *
	 * @dagewang 2017年9月19日
	 */
	@RequestMapping("/uploadImg")
	public @ResponseBody Map<String, Object> uploadImg(HttpSession session, MultipartFile img,
			HttpServletRequest httpServletRequest) throws Exception {
		User user = (User) session.getAttribute("user");
		Map<String, Object> map = new HashMap<String, Object>();
		if (user == null) {
			map.put("img", "");
			return map;
		}
		String newimg = null;
		if (img != null) {
			newimg = userService.uploadImg(img, httpServletRequest, "/file/userimg/", user.getId());
		}
		map.put("img", newimg);
		return map;

	}

	/**
	 * 退出登录
	 *
	 * @dagewang 2017年8月24日
	 */
	@RequestMapping("/outLogin")
	public String outLogin(HttpSession session) {
		session.setAttribute("user", null);
		return "redirect:/commodity/index.action";
	}

	/**
	 * 登录
	 *
	 * @dagewang 2017年8月24日
	 */
	@RequestMapping("/login")
	public String login(Model model, String username, String password, HttpSession session) throws Exception {
		User user = userService.get(username, password);
		if (user != null) {
			user.setUsername(null);
			user.setPassword(null);
			session.setAttribute("user", user);
			return "redirect:/commodity/index.action";
		} else {
			model.addAttribute("error", "用户名或密码错误");
		}
		return "login";
	}

	/**
	 * 异步登录
	 *
	 * @dagewang 2017年8月24日
	 */
	@RequestMapping("/loginAjax")
	public @ResponseBody Map<String, Object> loginAjax(String username, String password, HttpSession session)
			throws Exception {
		User user = userService.get(username, password);
		Map<String, Object> map = new HashMap<String, Object>();
		if (user != null) {
			user.setUsername(null);
			user.setPassword(null);
			session.setAttribute("user", user);
			map.put("result", 1);
		} else {
			map.put("result", "用户名或密码错误");
		}
		return map;
	}

	/**
	 * 用户注册
	 *
	 * @dagewang 2017年8月24日
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(HttpSession hs, User user) throws Exception {
		if (myUtil.isNull(user.getName(), user.getPassword(), user.getPhonenum(), user.getUsername())) {
			throw new MyException("接收不到您输入的值");
		}
		if (user.getName().equals("管理员") || user.getName() == "管理员") {
			return "register";
		}
		User user2 = userService.save(user);
		user2.setPassword(null);
		hs.setAttribute("user", user2);
		return "redirect:/commodity/index.action";
	}

	@RequestMapping("/isUser")
	public @ResponseBody Map<String, Object> isUser(String username) {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = userService.getUser(username);
		if (user == null) {
			map.put("result", "可用");
		} else {
			map.put("result", "不可用");
		}
		return map;
	}

	/**
	 * 如果id不为空的话,那么就把域对象里面的替换成我们查询到的user,在给其他的方法使用,这样在修改参数的时候就不会把不修改的变成空了
	 * 
	 * @throws Exception
	 * 
	 * @dagewang 2017年7月30日
	 */
	@ModelAttribute
	public void getUser(@RequestParam(value = "id", required = false) Integer id, Map<String, User> map)
			throws Exception {
		if (id != null && id.equals("")) {
			User user = userService.getUser(id);
			map.put("user", user);
		}
	}

	/**
	 * 添加用户
	 * 
	 * @Validated是指定使用哪个分组的校验注解,BindingResult是校验错误的返回值对象
	 * @dagewang 2017年7月30日
	 */
	/*
	 * @RequestMapping(value = "/saveUser", method = RequestMethod.POST) public
	 * String saveUser(HttpSession httpSession,Model model,
	 * 
	 * @Validated(value={ValidGroup1.class}) User user,BindingResult b ) throws
	 * Exception { if(b.hasErrors()){ List<ObjectError> allErrors =
	 * b.getAllErrors(); model.addAttribute("allErrors", allErrors); return
	 * "register"; } User newuser = userService.savaUser(user.getName(),
	 * user.getUsername(), user.getPassword()); httpSession.setAttribute("user",
	 * newuser); return "index";
	 * 
	 * }
	 */

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public MyUtil getMyUtil() {
		return myUtil;
	}

	public void setMyUtil(MyUtil myUtil) {
		this.myUtil = myUtil;
	}

}
